/*************************************************************************
	> File Name: exchange.cpp
	> Author: xuwenlong
	> Mail: myxuan475@126.com 
	> Created Time: 2018年09月29日 星期六 11时19分00秒
 ************************************************************************/
#include "exchange.h"
#include <transport/http/http.h>

Exchange::Exchange():
    m_pClientServer(new DasServer(this)),
    m_pCustomServer(new CustomServer(this)),
    m_pTimer(new Timer("exchange",this))
{

}

Exchange::~Exchange()
{
    StopServer();
    delete m_pClientServer;
    delete m_pCustomServer;
}

void Exchange::StartServer()
{
    m_pClientServer->StartServer(NETWAY_PORT);
    m_pCustomServer->StartServer(USER_PORT);
#ifdef LOCAL_TEST
//    m_pTimer->Start(60000,kPeriodic);
#else
//    m_pTimer->Start(600000,kPeriodic);
#endif
}

void Exchange::StopServer()
{
    m_pClientServer->StopServer();
    m_pCustomServer->StopServer();
}

void Exchange::RunTimer()
{
    time_t now = time(NULL);
    struct tm *tm2;
    tm2 = localtime(&now);
#ifdef LOCAL_TEST
    if (!(tm2->tm_hour == 14 && tm2->tm_min>19 && tm2->tm_min<=55))
        return;
    Http http("https://oapi.dingtalk.com/robot/send?access_token=b3da6004c4bc3e1ca87904697184b7e941d8284ba91364ae332a9a8045b64cd8");
#else
    if (!(tm2->tm_hour == 8 && tm2->tm_min>49 && tm2->tm_min<=59))
        return;
    Http http("https://oapi.dingtalk.com/robot/send?access_token=ddc6a2cbf26e97bad7e8a2a85f8b41cc5b815de9bda78d163dedf32c46b3f58c");
#endif
    Json::Value params;
    Json::Value markdown;

    params["msgtype"] = "markdown";

    string title,text;
    title = utils::todaytostr()+ " 网关状态汇报";
    markdown["title"] = title;

    text ="# "+title+"\n";
    text += "(网关汇报仅作参考，对于因网络问题未上报的项目和网关可能遗漏)\n";
    text += m_pClientServer->Report("## ");
    markdown["text"] = text;

    params["markdown"] = markdown;

    http.PostJson(params);
}

BOOL Exchange::OnReceiveJson(S32 index,DAS_RESULT status, const string &method, const Json::Value &result)
{
    return TRUE;
}

S32 Exchange::requestAcquisitor(JsonRpcInterface *_interface,
                                 const string &strId,
                                 const string &method,
                                 const Json::Value &params)
{

    tUser user = m_pClientServer->FindClient(strId);
    if (!user.valid())
        return -1;
    Client *client = static_cast<Client*>(user.get());
    return client->SendJsonRpc(_interface,method,params);
}

DAS_RESULT Exchange::getAcquisitorList(const Json::Value &params, Json::Value &result)
{
    return m_pClientServer->getAcquisitorList(params,result);
}

int Exchange::getPort(const string &strId, int type)
{
    tUser user = m_pClientServer->FindClient(strId);
    if (!user.valid())
        return -1;
    Client *client = static_cast<Client*>(user.get());
    return client->GetPort(type);
}
